package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.activity.NaviMapActivity;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.MonitoringDequiAdapter;
import com.mingtu.jgspatrol.bean.VideoListBean2;
import com.mingtu.jgspatrol.databinding.FragmentMonitoringDequiBinding;
import com.mingtu.hikvideo2.activity.NewPreviewActivity;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;

public class MonitoringDequiFragment extends BaseBindingFragment<FragmentMonitoringDequiBinding> implements LazyFragmentPagerAdapter.Laziable {
    
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private String type;
    private static final String ARG_PARAM = "param";
    private MonitoringDequiAdapter monitoringDequiAdapter;
    private String deptName = null;

    public static MonitoringDequiFragment getInstance(String id) {
        MonitoringDequiFragment ef = new MonitoringDequiFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM, id);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getString(ARG_PARAM);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_monitoring_dequi;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());
        //添加自定义分割线
//        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
//        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_dive_line));
//        binding.recycler.addItemDecoration(divider);


        monitoringDequiAdapter = new MonitoringDequiAdapter(context);
        if (isOpenLoadAnimation) {
            monitoringDequiAdapter.isFirstOnly(isFirstOnly);
            monitoringDequiAdapter.openLoadAnimation(animationType);
        }
        monitoringDequiAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(monitoringDequiAdapter);
        monitoringDequiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                VideoListBean2.PageBean.ListBean listBean = monitoringDequiAdapter.getData().get(position);
                String code = listBean.getCode(); //视频的code
                String title = listBean.getName(); //视频的title
                getRtspUrl(code, title);
            }
        });
        monitoringDequiAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                VideoListBean2.PageBean.ListBean listBean = monitoringDequiAdapter.getData().get(position);
                String lngStr = listBean.getLng();
                String latStr = listBean.getLat();
                switch (view.getId()) {
                    case R.id.layout_nav:
                        Bundle bundle = new Bundle();
                        bundle.putString("lng", lngStr);
                        bundle.putString("lat", latStr);
                        bundle.putBoolean("isFire", false);
                        IntentUtils.getInstance().readyGo(getActivity(), NaviMapActivity.class, bundle);
                        break;
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getCameraList(1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //处理完之后刷新数据
        String messgae = event.getMessgae();
        if (messgae.equals("全部")) {
            deptName = null;
        } else {
            deptName = messgae;
        }
        getCameraList(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getCameraList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(monitoringDequiAdapter.getData(), Constant.PAGE_SIZE);
                    getCameraList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 保护站下面的摄像头列表
     */
    private void getCameraList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        if (deptName != null) {
            hashMap.put("deptName", deptName);
        }
        hashMap.put("type", type);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_CAMERA_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            VideoListBean2 videoListBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                videoListBean = new VideoListBean2();
                                videoListBean = gson.fromJson(result, VideoListBean2.class);
                                List<VideoListBean2.PageBean.ListBean> dataBeans = videoListBean.getPage().getList();

                                if (dataBeans != null) {
                                    isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                    //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                    if (currentPage == 1) {
                                        monitoringDequiAdapter.replaceData(dataBeans);
                                    } else {
                                        monitoringDequiAdapter.addData(dataBeans);
                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }


                        }
                    }
                });
    }

    /**
     * 根据视频监控编号查询rstp地址
     */
    private void getRtspUrl(String code, String title) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", code);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_PREVIEW_URL)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();//{"msg":"success","code":0,"status":"rtsp://123.7.84.20:554/openUrl/9M1VWDu"}
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals("success")) {
                                String vodeoUrl = jsonObject.getString("status");
                                if (StringUtils.isEmpty(vodeoUrl)) {
                                    ToastUtils.showLong("未获取到视频链接！");
                                    return;
                                }
                                Bundle bundle = new Bundle();
                                bundle.putString("videoUrl", vodeoUrl);
                                bundle.putString("title", title);
                                bundle.putString("code", code);
//                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), VideoPlay2Activity.class, bundle);
//                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), WebViewActivity.class, bundle);
                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), NewPreviewActivity.class, bundle);

                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

}